package com.jsonal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsonal.common.CommonUtil;
import com.jsonal.common.DelFlagEnum;
import com.jsonal.entity.SysFileDt;
import com.jsonal.entity.Video;
import com.jsonal.entity.VideoBean;
import com.jsonal.mapper.SysFileDtMapper;
import com.jsonal.mapper.VideoMapper;
import com.jsonal.service.VideoService;
import com.jsonal.vo.Result;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: jsonal
 * @Description:
 * @Date: 2020/12/29 14:33
 * @Version: 1.0
 */
@Service
@Slf4j
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private SysFileDtMapper sysFileDtMapper;

    @Override
    public Result addOrUpdate(VideoBean videoBean) {
        Result result = new Result();
        Video video = new Video();
        BeanUtils.copyProperties(videoBean, video);
        if ((videoBean.getId() != null) && !"".equals(videoBean.getId())) {
            try {
                int update = videoMapper.updateById(video);
            } catch (Exception e) {
                e.printStackTrace();
                log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>更新数据失败，请重试！！！");
                result.setSuccess(false);
                result.setMsg("更新数据失败");
                return result;
            }
            result.setSuccess(false);
            result.setMsg("更新成功");
        } else {
            video.setId(CommonUtil.getGUID());
            video.setCreateTime(new Date());
            video.setDelFlag(DelFlagEnum.create.getValue());
            try {
                SysFileDt fileDt = sysFileDtMapper.selectOne(
                    new QueryWrapper<SysFileDt>().eq("file_dt_id", videoBean.getFileDtId()));
                fileDt.setRelevanceId(video.getId());
                sysFileDtMapper.update(fileDt,
                    new QueryWrapper<SysFileDt>().eq("file_dt_id", videoBean.getFileDtId()));
                videoMapper.insert(video);
                result.setMsg("新增数据成功");
                result.setSuccess(true);
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>新增数据失败");
                result.setSuccess(false);
                result.setMsg("新增数据失败");
            }
        }
        return result;
    }

    @Override
    public Result getVideoByPage(VideoBean videoBean) {
        Result result = new Result();
        Video video = new Video();
        BeanUtils.copyProperties(videoBean, video);
        List<VideoBean> videos = new ArrayList<>();
        IPage<Video> page = new Page<>(videoBean.getPage(), videoBean.getPageSize());
        if (!"".equals(videoBean.getQuery()) && videoBean.getQuery() != null) {
            IPage<Video> iPage = videoMapper.selectPage(page,
                new QueryWrapper<Video>().eq("del_flag", 0)
                    .and(i -> i.like("name", videoBean.getQuery())));
            videos = setFileUrl(iPage);

        } else {
            IPage<Video> iPage = videoMapper.selectPage(page,
                new QueryWrapper<Video>().eq("del_flag", 0));
            videos = setFileUrl(iPage);
        }
        result.setResults(videos);
        result.setSuccess(true);
        result.setMsg("获取成功");
        return result;
    }

    /**
     * 根据 id 删除（逻辑）视频
     * @param id 唯一标识
     * @return 返回删除结果
     */
    @Override
    public Result deleteVideoById(String id) {
        Result result = new Result();
        // 根据 id 查询视频数据
        Video video = videoMapper.selectById(id);
        if (video == null) {
            return new Result(false, "该id无效！");
        }
        // 因为文件表与视频表有关联id 所以也把文件表删了
        SysFileDt fileDt = sysFileDtMapper
            .selectOne(new QueryWrapper<SysFileDt>().eq("relevance_id", video.getId()));
        if (fileDt != null) {
            fileDt.setDelFlag(true);
            video.setDelFlag(1);
            videoMapper.updateById(video);
            sysFileDtMapper.update(fileDt, new QueryWrapper<SysFileDt>().eq("file_dt_id", fileDt.getFileDtId()));
            result.setMsg("删除成功");
            result.setSuccess(true);
            return result;
        }
        result.setSuccess(false);
        result.setMsg("删除失败");
        return result;
    }

    private List<VideoBean> setFileUrl(IPage<Video> iPage) {
        List<VideoBean> videos = new ArrayList<>();
        iPage.getRecords().forEach(item -> {
            VideoBean bean = new VideoBean();
            BeanUtils.copyProperties(item, bean);
            SysFileDt fileDt = sysFileDtMapper
                .selectOne(new QueryWrapper<SysFileDt>().eq("relevance_id", item.getId()));
            bean.setFileUrl(fileDt.getFileUrl());
            bean.setExtension(fileDt.getFileExtension());
            Integer size = Double.valueOf(fileDt.getFileSize()).intValue();
            double sizeMb = size / 1024 / 1024;
            log.info("size>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", size);
            log.info("size>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", sizeMb);
            bean.setFileSize(String.valueOf(sizeMb));
            videos.add(bean);
        });
        return videos;
    }
}
